package com.aven.blog.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
    private static SessionFactory sessionFactory;
    static {
        try {
            //加载配置
            Configuration configure = new Configuration().configure();
            //创建sessionFactory
            sessionFactory = configure.buildSessionFactory();
            //在虚拟机关闭时，释放sessionFactory
            Runtime.getRuntime().addShutdownHook(new Thread(){
                @Override
                public void run() {
                    sessionFactory.close();
                    System.out.println("释放资源。");
                }
            });
        }catch (Exception e){
            System.out.println("hibernateutils出错\n");
        }


    }//static
    public static Session openSession(){   //开启session
        return sessionFactory.openSession();
    }
    public static Session getCurrentSession(){
        return sessionFactory.getCurrentSession();
    }
}
